package com.tools.hry.xls.create.util;

import com.tools.hry.utils.BaseUtils;
import com.tools.hry.xls.create.DataSet;
import com.tools.hry.xls.analysis.annotation.ExcelProperty;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 峥桂 on 2017/9/6
 */
public class CreateExcelUtils {

    private static final String HEADER_NAME_TYPE_ZH_CN="ZH_CN";
    private static final String HEADER_NAME_TYPE_EN="EN";
    private static final String FIELD_TYPE_NAME="Field_type";

    public static DataSet createXlsDataSet(List list) throws Exception{
        if(list==null||list.size()==0){
            return null;
        }
        String[]  headers_en=getHeaders(list.get(0).getClass(),HEADER_NAME_TYPE_EN);
        String[]  headers_zh_cn=getHeaders(list.get(0).getClass(),HEADER_NAME_TYPE_ZH_CN);
        String[]  type_names=getHeaders(list.get(0).getClass(),FIELD_TYPE_NAME);
        List<String[]> dataList=convertDataList(list,headers_en,type_names);
        DataSet dataSet=new DataSet(headers_zh_cn,dataList);
        return dataSet;
    }

    public static DataSet createXlsDataSet(String[] headers,List<String[]> dataList) {
        return new DataSet(headers,dataList);
    }

    private static List<String[]> convertDataList(List list,String[] headers,String[]  type_names) throws Exception{
        List<String[]> dataList=new ArrayList<String[]>();
        String[] rows;
        int index; Map<?,?> map; Object value;String fieleTypeName;
        for (Object obj:list) {
            if(obj==null){
                continue;
            }
            map= BaseUtils.objectToMap(obj);
            index=0;//恢复到准备一行数据的第一个位置
            rows=new String[headers.length];//根据header位置 存放对应的列值数据准备
            for(String key:headers){
               value=map.get(key);
                if(value!=null){
                    fieleTypeName=type_names[index];
                    value=BaseUtils.handleFieldTypeValue(fieleTypeName,value.toString());
                    rows[index]=value.toString();
                }
                index++;
            }
            dataList.add(rows);
        }
        return dataList;
    }

    public static String[] getHeaders(Class tClass,String header_name_type){
        Field[] fields=tClass.getDeclaredFields();
        List<String> list=new ArrayList<String>();
        for(Field field:fields){
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            if(excelProperty==null){
                continue;
            }
            if(HEADER_NAME_TYPE_EN.equals(header_name_type)){
                list.add(field.getName());//取值列的英文
            }else if(FIELD_TYPE_NAME.equals(header_name_type)){
                list.add(field.getType().getName());//取值列的英文
            }else{
                list.add(excelProperty.value());//取值列的中文名
            }

        }
        return list.toArray(new String[list.size()]);
    }
}
